<?php
class Pagination {
	var $tag_name = "page";
	var $page_size = 10;
	var $total_row = 0;
	var $total_page = 0;
	var $paging = 1;		// 呼叫页号
 	var $url = '';			// url地址头
 	var $start_row = 0;
 	var $params = array();
	
	function Pagination($params = array()) {
		if (count($params) > 0) {
			$this->init($params);		
		}
	}
 	
	function init( $params = array() ) {
		if ( count($params) > 0 ) {   
    		foreach ($params as $key => $val) {
      			$this->$key = $val;
      		}        
    	}
		$this->set_up();
	}
	
	function set_up() {
		$this->total_page = floor( ( $this->total_row + ($this->page_size - 1) ) / $this->page_size );
		
		if( isset( $_GET[ $this->tag_name ] ) ) {
			$this->paging = $_GET[ $this->tag_name ];	
		}
		else if( isset( $_POST[ $this->tag_name ] ) ) {
			$this->paging = $_POST[ $this->tag_name ];
		}
		
		$this->start_row = ( $this->paging - 1) * $this->page_size;	
		
		($this->url == '') ? $this->_auto_url() : $this->_manual_url();
	}

	function do_page() {	
		if( $this->total_page <= 1 ) {
			return;
		}
		return $this->pre_page() . $this->content_page() . $this->next_page();
	}
	
	/**
	 * 手动创建url
	 * @return void
	 */
	function _manual_url() {
		if( count( $this->params ) == 0 ) {
			$this->url .= '?' . $this->tag_name . '=';	
		}
		else {
			$this->url .= '?' . join('&', $this->params) . '&' . $this->tag_name . '=';
		}
	}
	
	/**
	 * 自动创建url
	 * @return void
	 */
	function _auto_url() {
		if( empty($_SERVER['QUERY_STRING']) ) {
			$this->url=$_SERVER['REQUEST_URI'].'?' . $this->tag_name . '=';
		}
		else {
			if( strpos( $_SERVER['REQUEST_URI'], $this->tag_name . '=') ) {
				$temp_uri = str_replace( $this->tag_name . '=' . $this->paging, '', $_SERVER['REQUEST_URI'] );
				$this->url = $temp_uri .  $this->tag_name . '=';
			}
			else {
				$this->url=$_SERVER['REQUEST_URI'].'&' . $this->tag_name."=";
			}
		}
	}
	
	function pre_page() {
		if( $this->paging > 1 ) {
			$str = "<a href='". $this->url . ($this->paging - 1) ."'>上一页</a>";
		}
		else {
			$str = "<span>上一页</span>";
		}
		return $str;
	}
	
	function next_page() {
		if( $this->paging < $this->total_page ) {
			$str = "<a href='". $this->url . ($this->paging + 1) ."'>下一页</a>";
		}
		else {
			$str = "<span>下一页</span>";
		}
		return $str;
	}
	
	function content_page() {
		$start_page = $this->paging - 5;
		if( $start_page < 1 ) {
			$start_page = 1;
		} 

		$end_page = $this->paging + 5;
		if( $end_page > $this->total_page ) {
			$end_page = $this->total_page;
		}

		$str = "";
		for( $i = $start_page; $i <= $end_page; $i++ ) {
			if( $i == $this->paging ) {
				$str .= "<span class='current'>" . $i . "</span>";
			}
			else {
				$str .= "<a href='". $this->url . $i ."'>$i</a>";
			}
		}
		return $str;
	}
	
}

?>